package com.fumin.filter;

import com.fumin.common.RequestHolder;
import com.fumin.model.SysUser;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 判断用户是否登录的FILTER
 * 如果用户未登录,则直接跳转到登录界面;
 * 已经登录,则从session中取出sysUser对象,放入到进程的ThreadLocal中,以后取sysUser的时候,都直接从ThreadLocal中取即可
 * @Author xiayuxuanmin
 * @Date 2019/10/27
 * @Description
 */
@Slf4j
//注意:写了filter之后,必须要去web.xml中配置,配置filter要拦截哪些请求
public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println();
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        SysUser sysUser = (SysUser)request.getSession().getAttribute("user");
        if (sysUser == null) {
            String path = "/signin.jsp";
            response.sendRedirect(path);
        }
        RequestHolder.add(sysUser);
        RequestHolder.add(request);
        filterChain.doFilter(servletRequest,servletResponse);
        return;
    }

    @Override
    public void destroy() {

    }
}
